package com.yoo.ons.function.home

import android.net.Uri
import android.os.Bundle
import android.text.style.ForegroundColorSpan
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.lifecycle.ViewModelProvider
import com.gyf.immersionbar.ImmersionBar
import com.yoo.chat.kit.IMCenter
import com.yoo.chat.kit.RongIM
import com.yoo.chat.kit.utils.RouteUtils
import com.yoo.module_base.R
import com.yoo.module_base.base.BaseDialogFragment
import com.yoo.module_base.utils.setOnClickCallback
import com.yoo.module_base.view.Spanny
import com.yoo.ons.AppUserViewModel
import com.yoo.ons.base.HttpRequestListener
import com.yoo.ons.databinding.DialogFragmentFlashChatBinding
import com.yoo.ons.function.home.viewmodel.HomeViewModel
import com.yoo.ons.function.me.like.MyLikeListViewModel
import com.yoo.ons.util.ImageCached.getColor
import com.yoo.ons.util.Injections.mainHandler
import com.yoo.ons.util.load
import io.rong.imlib.IRongCallback
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message
import io.rong.imlib.model.UserInfo
import io.rong.message.TextMessage

/**
 * flashchat page
 */
class FlashChatDialogFragment : BaseDialogFragment() {
    private var innerBinding: DialogFragmentFlashChatBinding? = null
    private val binding get() = innerBinding!!
    private val toUserId by lazy { arguments?.getString(FLASH_CHAT_TO_USER_ID)!! }
    private val toUserImg by lazy { arguments?.getString(FLASH_CHAT_TO_USER_HEAD)!! }
    private val toUserName by lazy { arguments?.getString(FLASH_CHAT_TO_USER_NAME)!! }
    private val appUserViewModel by lazy { AppUserViewModel.get() }
    private val homeViewModel by lazy {
        ViewModelProvider(requireActivity())[HomeViewModel::class.java]
    }
    private val myLikeListViewModel by lazy {
        ViewModelProvider(requireActivity())[MyLikeListViewModel::class.java]
    }
    private var msgData: String? = null
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        innerBinding = innerBinding
            ?: DialogFragmentFlashChatBinding.inflate(inflater, container, false)
        return binding.root
    }


    override fun setWindow(win: Window) {
        win.setWindowAnimations(R.style.DialogAnimation)
        win.decorView.setPadding(0, 0, 0, 0)
        val lp = win.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.MATCH_PARENT
        win.attributes = lp
        win.setGravity(Gravity.BOTTOM)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData()
    }

    private fun initData() {
        //点击跳转私信
        appUserViewModel.postFlashChatMsg {
            msgData = it
        }
        binding.imgFlashChatBackground.load(toUserImg)
        val txtSpannableContent = Spanny().append("Ready for an exciting chat witch ")
            .append(toUserName, ForegroundColorSpan(getColor("#FF3EAB")))
            .append(" Start a flash chat now!")
        binding.txtFlashChatContent.text = txtSpannableContent
        binding.imgFlashChatClose.setOnClickCallback { dismiss() }
        binding.txtFlashChatStart.setOnClickCallback {
            goToChat(msgData ?: "")
            appUserViewModel.postReduceBenefits(object : HttpRequestListener<String>() {
                override fun addRequestParams(params: HashMap<String, Any>) {
                    params["benefitCode"] = 1
                    params["chatUserCode"] = toUserId
                }

                override fun success(t: String?) {
                }
            }) {
//                //消费成功
//                //点击的时候需要去移除首页划卡
//                homeViewModel.clickHomeFc(true)
//                goToChat(msgData ?: "")
            }
        }
    }

    private fun goToChat(data: String) {
        val context = activity ?: return
        RongIM.getInstance().refreshUserInfoCache(
            UserInfo(toUserId, toUserName, Uri.parse(toUserImg))
        )
        val message: Message = Message.obtain(
            toUserId,
            Conversation.ConversationType.PRIVATE,
            TextMessage.obtain(data)
        )
        IMCenter.getInstance()
            .sendMessage(message, null, null, object : IRongCallback.ISendMessageCallback {
                override fun onAttached(message: Message?) {}
                override fun onSuccess(message: Message?) {
                }

                override fun onError(message: Message?, errorCode: RongIMClient.ErrorCode?) {}
            })
        val bundle = Bundle()
        bundle.putBoolean("flashClick", true)
        RouteUtils.routeToConversationActivity(
            context,
            Conversation.ConversationType.PRIVATE,
            toUserId, bundle
        )
        //延迟关闭弹窗和发送首页划卡动作
        mainHandler.postDelayed({
            //点击了ilike的fc弹窗里面的start进行列表移除item
            myLikeListViewModel.removeModel(toUserId)
            //点击了首页卡片fc弹窗里面的start进行列表移除item
            homeViewModel.clickHomeFc(true)
            dismissAllowingStateLoss()
        }, 500)

    }

    override fun onResume() {
        super.onResume()
        ImmersionBar.with(this).statusBarDarkFont(false).init()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        homeViewModel.clickHomeFc(false)
        innerBinding = null
        dismissAllowingStateLoss()
    }

    companion object {
        private const val FLASH_CHAT_TO_USER_ID = "FLASH_CHAT_TO_USER_ID"
        private const val FLASH_CHAT_TO_USER_HEAD = "FLASH_CHAT_TO_USER_HEAD"
        private const val FLASH_CHAT_TO_USER_NAME = "FLASH_CHAT_TO_USER_NAME"
        fun newInstance(
            imgUrl: String,
            toUserId: String,
            toUserName: String
        ): FlashChatDialogFragment {
            return FlashChatDialogFragment().apply {
                arguments = Bundle().apply {
                    putString(FLASH_CHAT_TO_USER_HEAD, imgUrl)
                    putString(FLASH_CHAT_TO_USER_ID, toUserId)
                    putString(FLASH_CHAT_TO_USER_NAME, toUserName)
                }
            }
        }
    }
}